<template>
    <my-dialog 
    v-model="model" 
    title="新建"
    width="400px"
    :wide="false"
    >
        <el-form 
        class="name-form"
        ref="form"
        :model="form" 
        label-position="top"
        size="small"
        >
            <el-form-item label="新建文件名" prop="filename" :rules="[{validator: fileNameCheck,trigger:['blur', 'change']}]">
                <el-input v-model="form.filename"></el-input>
            </el-form-item>

            <div class="btns">
                <el-button size="small" @click="closeHandler">取消</el-button>
                <el-button size="small" type="primary" @click="submitHandler">确定</el-button>
            </div>
        </el-form>
    </my-dialog>
</template>

<script>
export default {
    props: {
        value: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            form: {
                filename: '',
            },
        };
    },
    computed: {
        model: {
            get() {
                return this.value;
            },
            set(val) {
                this.$emit('input', val);
            },
        },
    },
    watch: {
        model(n) {
            if (!n) {
                this.$refs.form.resetFields();
            }
        }
    },
    methods: {
        fileNameCheck(rule, value, callback) {
            if (!value) {
                callback(new Error('请输入文件名'));

                return;
            }

            if (value.length > 30) {
                callback(new Error('文件名称不能超过30个字'));

                return;
            }

            if (/^ /.test(value)) {
                callback(new Error('文件名不能以空格开头'));
            }

            if (!/^[^/\\\\:\\*\\?\\<\\>\\|\"]{1,255}$/.test(value)) {
                callback(new Error('文件名不能包含下列任何字符：\\/:*?"<>|'));

                return;
            }

            this.$get(`${this.$store.state.api.sysUrl}/file/bidding/plan/checkname.json`, {
                name: this.form.filename,
            }, data => {
                if (data) {
                    callback();
                } else {
                    callback(new Error('该文件名称已存在于云盘'));
                }
            });
        },
        submitHandler() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.$emit('submit', this.form.filename);
                    this.closeHandler();
                }
            });
        },
        closeHandler() {
            this.model = false;
        },
    },
}
</script>

<style lang="scss" scoped>
    .name-form{
        margin-top: -30px;
    }

    .btns{
        text-align: right;
    }
</style>